package com.wshl.cloudservice.activities;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.text.TextUtils;
import android.util.Log;
import android.view.SurfaceView;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.VideoView;

import androidx.appcompat.widget.AppCompatImageView;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.blankj.utilcode.util.KeyboardUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.NetworkUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.bumptech.glide.Glide;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.wshl.cloudservice.CloudServiceApplication;
import com.wshl.cloudservice.Constants;
import com.wshl.cloudservice.R;
import com.wshl.cloudservice.adapter.MsgListAdapter;
import com.wshl.cloudservice.ui.widget.DragFrameLayout;
import com.wshl.cloudservice.ui.widget.LoadingDialog;
import com.wshl.cloudservice.utils.SoftKeyBoardListener;
import com.wshl.cloudservice.utils.WindowUtil;

import org.json.JSONException;
import org.json.JSONObject;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

import io.agora.rtc.RtcEngine;
import io.agora.rtm.ErrorInfo;
import io.agora.rtm.LocalInvitation;
import io.agora.rtm.RemoteInvitation;
import io.agora.rtm.ResultCallback;
import io.agora.rtm.RtmMessage;
import io.agora.rtm.SendMessageOptions;

public class VideoActivity extends BaseCallActivity {
    private static final String TAG = "openduo";

    private DragFrameLayout mLayoutSmallView;
    private FrameLayout mLayoutBigView;

    private AppCompatImageView mMuteBtn;
    private AppCompatImageView mCameraBtn;
    private TextView tvTime;
    private TextView tvShow;
    private RelativeLayout rlBottom;
    private EditText etComment;
    private RecyclerView mRecycle;
    private TextView tvServerNIckname;
    private ImageView imghead;
    private TextView tvServername;
    private TextView tvServerip;
    private String mChannel;
    private int mPeerUid;


    private boolean isLocalSmall = true;//本地预览是否是小窗 默认是true
    private int mRemoteUid;//远程主播的id
    private long baseTimer;
    private SoftKeyBoardListener softKeyBoardListener;
    private TextView tvSend;


    private MsgListAdapter mAdapter;
    private List<String> msgList = new ArrayList<>();


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //使用键盘监听，必须要设置这两个属性
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN | WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);

        //隐藏状态栏
        WindowUtil.hideWindowStatusBar(getWindow());
        setContentView(R.layout.activity_video);
        initUI();
        initVideo();

    }

    private void initUI() {

        mLayoutSmallView = findViewById(R.id.local_preview_layout);
        mLayoutBigView = findViewById(R.id.remote_preview_layout);
        mCameraBtn = findViewById(R.id.btn_camera);
        mMuteBtn = findViewById(R.id.btn_mute);
        tvTime = findViewById(R.id.tv_time);
        tvShow = findViewById(R.id.tv_show);
        rlBottom = findViewById(R.id.rl_bottom);
        etComment = findViewById(R.id.et_msg);
        tvSend = findViewById(R.id.tv_send);
        tvServerNIckname = findViewById(R.id.tv_server_nickname);
        mRecycle = findViewById(R.id.recycle_msg);
        tvServerip = findViewById(R.id.tv_server_id);
        tvServername = findViewById(R.id.tv_server_nickname);
        imghead = findViewById(R.id.img_server_head);

        if (!TextUtils.isEmpty(global().getPeerAvatar())) {
            Glide.with(this).load(CloudServiceApplication.BASEURL + "/upload/" + global().getPeerAvatar()).into(imghead);
        }

        LogUtils.i(global().getPeerNIckname());
        if (!TextUtils.isEmpty(global().getPeerNIckname())) {
            tvServername.setText(global().getPeerNIckname() + "");
        }

        tvServerip.setText("ID:" + global().getPeerId());

        mRecycle.setHasFixedSize(true);
        mRecycle.setNestedScrollingEnabled(false);
        mRecycle.setEnabled(false);
        //设置聊天消息列表
        LinearLayoutManager layoutManager=new LinearLayoutManager(this);
        mRecycle.setLayoutManager(layoutManager);
        mAdapter = new MsgListAdapter(this, msgList);
        mRecycle.setAdapter(mAdapter);


        setSoftKeyBoardListener();
    }

    @Override
    protected void onGlobalLayoutCompleted() {
  /*      RelativeLayout.LayoutParams params =
                (RelativeLayout.LayoutParams) mLayoutSmallView.getLayoutParams();
        params.topMargin += statusBarHeight;
        mLayoutSmallView.setLayoutParams(params);

        RelativeLayout buttonLayout = findViewById(R.id.button_layout);
        params = (RelativeLayout.LayoutParams) buttonLayout.getLayoutParams();
        params.bottomMargin = displayMetrics.heightPixels / 8;
        params.leftMargin = displayMetrics.widthPixels / 6;
        params.rightMargin = displayMetrics.widthPixels / 6;
        buttonLayout.setLayoutParams(params);*/
    }

    private void initVideo() {
        Intent intent = getIntent();
        mChannel = intent.getStringExtra(Constants.KEY_CALLING_CHANNEL);
        try {
            mPeerUid = Integer.valueOf(intent.getStringExtra(Constants.KEY_CALLING_PEER));
        } catch (NumberFormatException e) {
            Toast.makeText(this, R.string.message_wrong_number,
                    Toast.LENGTH_SHORT).show();
            e.printStackTrace();
        }
//        rtcEngine().enableWebSdkInteroperability(true);
        RtcEngine rtcEngine = rtcEngine();
        Log.i(TAG, "initVideo: " + rtcEngine);
        //设置模式为 直播模式
        rtcEngine.setChannelProfile(io.agora.rtc.Constants.CHANNEL_PROFILE_LIVE_BROADCASTING);
        //设置身份为主播
        rtcEngine().setClientRole(io.agora.rtc.Constants.CLIENT_ROLE_BROADCASTER);
        setVideoConfiguration();

        //由于刚开始相机和麦克风都是默认关闭的，因此不需要初始化预览
        // setupLocalPreview();

        // ToastUtils.showLong("rtc登录的uid:" + global().getmUserId());
        joinRtcChannel(mChannel, "", Integer.parseInt(global().getmUserId()));
    }


    /**
     * 隐藏文字消息
     */
    private void hideMsg() {

       /*  mRecycle.setVisibility(View.GONE);
        tvShow.setVisibility(View.GONE);
        rlBottom.setVisibility(View.GONE);
        KeyboardUtils.hideSoftInput(this);
        etComment.setText("");*/
    }

    /**
     * 显示文字消息
     */
    private void showMsg() {
/*
        mRecycle.setVisibility(View.VISIBLE);
        tvShow.setVisibility(View.VISIBLE);*/
    }

    /**
     * 开启本地视频预览
     */
    private void setupLocalPreview() {


        //判断摄像头是否时开启，只有开启状态下才加载小窗
        if (!mCameraBtn.isSelected()) {
            return;
        }

        //如果本地预览是小窗口
        if (isLocalSmall) {
            if (mLayoutSmallView.getChildCount() > 0) {
                mLayoutSmallView.removeAllViews();
            }
            SurfaceView surfaceView = setupVideo(Integer.parseInt(global().getmUserId()), true);
            surfaceView.setZOrderOnTop(true);
            mLayoutSmallView.addView(surfaceView);
        } else {
            // 如果本地预览是大窗口

            if (mLayoutBigView.getChildCount() > 0) {
                mLayoutBigView.removeAllViews();
            }
            SurfaceView surfaceView = setupVideo(Integer.parseInt(global().getmUserId()), true);
            mLayoutBigView.addView(surfaceView);

        }


    }

    /**
     * 开启远端主播窗口预览
     *
     * @param uid
     */
    private void setupRemoteView(int uid) {

        if (isLocalSmall) {
            //如果本地预览是小窗口，则远端是大窗口
            if (mLayoutBigView.getChildCount() > 0) {
                mLayoutBigView.removeAllViews();
            }
            SurfaceView surfaceView = setupVideo(uid, false);
            mLayoutBigView.addView(surfaceView);
        } else {
            //如果本地预览是大窗口，则远端是小窗口

            if (mLayoutSmallView.getChildCount() > 0) {
                mLayoutSmallView.removeAllViews();
            }
            SurfaceView surfaceView = setupVideo(uid, false);
            surfaceView.setZOrderOnTop(true);
            mLayoutSmallView.addView(surfaceView);
        }

    }


    //计时器
    Handler myhandler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            if (0 == baseTimer) {
                baseTimer = SystemClock.elapsedRealtime();
            }

            int time = (int) ((SystemClock.elapsedRealtime() - baseTimer) / 1000);
            String mm = new DecimalFormat("00").format(time / 60);
            String ss = new DecimalFormat("00").format(time % 60);
            if (null != tvTime) {
                tvTime.setText(mm + ":" + ss);
            }
            Message message = Message.obtain();
            message.what = 0x0;
            sendMessageDelayed(message, 1000);
        }
    };

    /**
     * 开始计时
     */
    private void jishi() {

        this.baseTimer = SystemClock.elapsedRealtime();
        myhandler.sendMessageDelayed(Message.obtain(myhandler, 1), 1000);
    }

    @Override
    public void onLocalInvitationAccepted(LocalInvitation localInvitation, String response) {
        super.onLocalInvitationAccepted(localInvitation, response);
        Log.i(TAG, "onLocalInvitationAccepted: 远程主播接受了呼叫邀请");
    }

    @Override
    public void onUserJoined(final int uid, int elapsed) {
        Log.i(TAG, "远端用户加入了: " + uid + ":" + mPeerUid);
        // if (uid != mPeerUid) return;
        mRemoteUid = uid;
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
//                if (mLayoutBigView.getChildCount() == 0) {
//                    SurfaceView surfaceView = setupVideo(uid, false);
//                    mLayoutBigView.addView(surfaceView);
//                }
                //开始计时
                jishi();
                //展示远端画面
                setupRemoteView(uid);
            }
        });
    }


    @Override
    public void onUserOffline(int uid, int reason) {
        //  if (uid != mPeerUid) return;
        Log.i(TAG, "onUserOffline: 主播结束了通话");
        finish();
    }

    private boolean isOpenAudio = false;
    private boolean isOpenVideo = false;

    public void onButtonClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_send://发送消息

                String msgContent = etComment.getText().toString().trim();
                if (TextUtils.isEmpty(msgContent)) {
                    ToastUtils.showShort("请输入咨询内容");
                    return;
                }
                sendTextMsg(msgContent);
                KeyboardUtils.hideSoftInput(this);
                break;
            case R.id.tv_show://弹出输入框
                KeyboardUtils.showSoftInput(this);
                break;
            case R.id.btn_endcall://挂断
                sendTextMsg("hangup");
                finish();
                break;
            case R.id.btn_mute://打开/关闭麦克风
                Log.i(TAG, "onButtonClicked: " + mMuteBtn.isSelected());
                if (!mMuteBtn.isSelected()) {
                    isOpenAudio = true;
                    hideMsg();
                    //打开麦克风
                    sendTextMsg("openaudio");
                } else {
                    isOpenAudio = false;
                    if (!isOpenVideo) {
                        showMsg();
                    }
                    //关闭麦克风
                    sendTextMsg("closeaudio");
                }                //rtcEngine().enableLocalAudio(!mMuteBtn.isEnabled());
                rtcEngine().muteLocalAudioStream(mMuteBtn.isSelected());
                mMuteBtn.setSelected(!mMuteBtn.isSelected());
                break;
            case R.id.btn_camera://打开/关闭摄像头
                mCameraBtn.setSelected(!mCameraBtn.isSelected());
                if (mCameraBtn.isSelected()) {
                    isOpenVideo = true;
                    hideMsg();
                    //开启
                    setupLocalPreview();
                    rtcEngine().muteLocalVideoStream(false);
                    rtcEngine().enableLocalVideo(true);
                    //打开摄像头
                    sendTextMsg("openvideo");
                } else {
                    isOpenVideo = false;

                    //视频和音频同时关闭时，显示文字消息
                    if (!isOpenAudio) {
                        showMsg();
                    }

                    //关闭
                    closeLocalView();

                    rtcEngine().muteLocalVideoStream(true);
                    rtcEngine().enableLocalVideo(false);
                    //关闭摄像头
                    sendTextMsg("closevideo");
                }
                // rtcEngine().muteLocalVideoStream(mMuteBtn.isSelected());

                break;
            case R.id.btn_switch_camera://切换摄像头
                rtcEngine().switchCamera();

                break;
            case R.id.local_preview_layout://小窗口的切换

                //正在拖拽中，不能点击
                if (mLayoutSmallView.isDrag()) {
                    return;
                }

                if (isLocalSmall) {
                    //如果点击之前,小窗口显示的是本地预览

                    // 点击之后,
                    //大窗口变成,本地的预览
                    mLayoutBigView.removeAllViews();
                    SurfaceView surfaceView2 = setupVideo(Integer.valueOf(global().getmUserId()), true);
                    mLayoutBigView.addView(surfaceView2);
                    mLayoutBigView.setVisibility(View.VISIBLE);


                    //小窗口变成远程主播的画面
                    mLayoutSmallView.removeAllViews();
                    SurfaceView surfaceView = setupVideo(mRemoteUid, false);
                    surfaceView.setZOrderOnTop(true);
                    mLayoutSmallView.addView(surfaceView);

                    isLocalSmall = false;

                } else {

                    //点击之前,大窗口是本地预览

                    //点击之后
                    //大窗口变成远程主播画面
                    // setupRemoteView(mRemoteUid);
                    if (mLayoutBigView.getChildCount() > 0) {
                        mLayoutBigView.removeAllViews();
                    }
                    SurfaceView surfaceView = setupVideo(mRemoteUid, false);
                    mLayoutBigView.addView(surfaceView);


                    //小窗口变成本地预览
                    if (mLayoutSmallView.getChildCount() > 0) {
                        mLayoutSmallView.removeAllViews();
                    }

                    //如果本地摄像头没有开启，则不必显示本地预览
                    if (!isOpenVideo) {
                        isLocalSmall = true;
                        return;
                    }

                    SurfaceView surfaceView2 = setupVideo(Integer.parseInt(global().getmUserId()), true);
                    surfaceView2.setZOrderOnTop(true);
                    mLayoutSmallView.addView(surfaceView2);

                    //setupLocalPreview();

                    isLocalSmall = true;

                }
                break;

        }
    }

    /**
     * 关闭本地摄像头的预览
     */
    private void closeLocalView() {

        //如果本地预览是小窗口，则关闭小窗口
        if (isLocalSmall) {
            if (mLayoutSmallView.getChildCount() > 0) {
                mLayoutSmallView.removeAllViews();
            }
        } else {
            //如果本地预览是大窗口，则关闭大窗口
            if (mLayoutBigView.getChildCount() > 0) {
                mLayoutBigView.removeAllViews();
            }
            //然后关闭小窗口
            mLayoutSmallView.removeAllViews();
            //然后把大窗口显示成远端
            SurfaceView surfaceView = setupVideo(mRemoteUid, false);
            mLayoutBigView.addView(surfaceView);

            isLocalSmall = true;
        }
    }

    /**
     * 软键盘监听
     */
    private void setSoftKeyBoardListener() {
        softKeyBoardListener = new SoftKeyBoardListener(this);
        //软键盘状态监听
        softKeyBoardListener.setListener(new SoftKeyBoardListener.OnSoftKeyBoardChangeListener() {
            @Override
            public void keyBoardShow(int height) {

                //动态设置控件宽高
                ViewGroup.LayoutParams params = rlBottom.getLayoutParams();
                rlBottom.setPadding(0, 0, 0, height);
                rlBottom.setLayoutParams(params);
                //当软键盘显示的时候
                rlBottom.setVisibility(View.VISIBLE);
                tvShow.setVisibility(View.GONE);
                //tv_shape2.setVisibility(View.VISIBLE);

                etComment.requestFocus();
                etComment.setFocusable(true);
                etComment.setCursorVisible(true);
                etComment.setFocusableInTouchMode(true);

            }

            @Override
            public void keyBoardHide(int height) {

                //当软键盘隐藏的时候
                rlBottom.setVisibility(View.GONE);
                etComment.setText("");
                tvShow.setVisibility(View.VISIBLE);
            }
        });

    }

    @Override
    public void finish() {
        super.finish();
        leaveChannel();

        Intent intent = new Intent(VideoActivity.this, CommentActivity.class);
        intent.putExtra("token", global().getToken());
        intent.putExtra("avatar", global().getPeerAvatar());
        intent.putExtra("name", global().getPeerNIckname());
        startActivity(intent);
    }

    @Override
    public void onRemoteInvitationReceived(RemoteInvitation remoteInvitation) {
        // Do not respond to any other calls
        Log.i(TAG, "Ignore remote invitation from " +
                remoteInvitation.getCallerId() + " while in calling");
    }

    @Override
    public void onRemoteDecoding(final int uid, int state) {

        Log.i(TAG, "onRemoteDecoding: 获取到远端主播的第一帧:" + uid);

//        runOnUiThread(new Runnable() {
//            @Override
//            public void run() {
//                if (mLayoutBigView.getChildCount() == 0) {
//                    SurfaceView surfaceView = setupVideo(uid, false);
//                    mLayoutBigView.addView(surfaceView);
//                }
//            }
//        });
    }

    /**
     * 点对点消息监听
     *
     * @param rtmMessage
     * @param senduid
     */
    @Override
    public void onMessAgeReceive(RtmMessage rtmMessage, String senduid) {
        Log.i("openduo", "onMessageReceived: 收到一条点对点消息:" + rtmMessage.getText() + ";发送者uid:" + senduid);
        // ToastUtils.showLong("收到一条消息:" + rtmMessage.getText() + "发送者：" + senduid);
        final String msg = rtmMessage.getText();
        if (TextUtils.isEmpty(msg)) {
            return;
        }
        // openvideo,openaudio,closevideo,closeaudio,hangup
        switch (msg) {
            case "endCall":

                ToastUtils.showLong("客服结束了通话");
                finish();

                break;
            case "closevideo"://关闭摄像头

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {

                        isOpenVideo = false;
                        if (!isOpenAudio) {
                            showMsg();
                        }

                        rtcEngine().muteLocalVideoStream(true);
                        rtcEngine().enableLocalVideo(false);
                        mCameraBtn.setSelected(false);
                        //关闭本地预览
                        closeLocalView();
                    }
                });


                break;
            case "openvideo"://开启摄像头

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        isOpenVideo = true;
                        hideMsg();
                        rtcEngine().muteLocalVideoStream(false);
                        rtcEngine().enableLocalVideo(true);
                        mCameraBtn.setSelected(true);
                        //如果本地预览是小窗口，则开启小窗口
                        setupLocalPreview();


                    }
                });

                break;

            case "closeaudio"://关闭麦克风

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {

                        isOpenAudio = false;
                        if (!isOpenVideo) {
                            showMsg();
                        }

                        rtcEngine().muteLocalAudioStream(true);
                        // rtcEngine().enableLocalAudio(false);
                        mMuteBtn.setSelected(false);
                    }
                });

                break;

            case "openaudio"://开启麦克风

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        isOpenAudio = true;
                        hideMsg();
                        rtcEngine().muteLocalAudioStream(false);
                        // rtcEngine().enableLocalAudio(true);
                        mMuteBtn.setSelected(true);

                    }
                });

                break;
            case "hangup":
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {

                        ToastUtils.showLong("客服结束了通话");
                        finish();

                    }
                });
                break;
            default:

                //更新消息列表
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        msgList.add(global().getPeerNIckname() + "&" + msg);
                        mAdapter.notifyDataSetChanged();
                        mRecycle.scrollToPosition(msgList.size() - 1);

                    }
                });


                break;

        }


    }

    private void sendTextMsg(final String content) {

        final RtmMessage message = rtmClient().createMessage();
        message.setText(content);
        SendMessageOptions option = new SendMessageOptions();
        option.enableOfflineMessaging = false;//是否接受离线消息
        rtmClient().sendMessageToPeer(String.valueOf(mPeerUid), message, option, new ResultCallback<Void>() {
            @Override
            public void onSuccess(Void aVoid) {
                Log.i("openduo", "消息发送成功:" + mPeerUid + ";" + content);

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        // ToastUtils.showLong("消息发送成功:" + mPeerUid + ";" + content);
                        if (content.equals("closevideo") || content.equals("openvideo") || content.equals("closeaudio") || content.equals("openaudio")) {
                            return;
                        }

                        msgList.add(global().getmNickname() + "&" + content);
                        mAdapter.notifyDataSetChanged();
                        mRecycle.scrollToPosition(msgList.size() - 1);


                        sendMsg(content);
                    }
                });


            }

            @Override
            public void onFailure(ErrorInfo errorInfo) {
                ToastUtils.showLong("消息发送失败：" + errorInfo.getErrorDescription());
                Log.i("openduo", "点对点消息发送失败:" + errorInfo.getErrorDescription());
            }
        });
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        if (myhandler != null) {
            myhandler.removeCallbacksAndMessages(null);
        }
    }

    @Override
    public void onBackPressed() {
        String content = "正在通话中，是否要离开？";
        dialogUtils.showCustomdialog(this, content, false, true, "提示", "取消", "确定");
    }

    @Override
    public void setConfirm() {
        super.setConfirm();
        finish();
    }


    private void sendMsg(String text) {
        if (!NetworkUtils.isConnected()) {
            return;
        }
        String token = global().getToken();
        OkGo.<String>post(CloudServiceApplication.SENDMSG)
                .tag(this)
                .params("token", token)
                .params("text", text)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        LogUtils.i("发送消息：" + response.body());

                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        LogUtils.e("发送消息：" + response.code());
                    }
                });


    }
}
